#include "stdafx.h"

extern "C"{
	#include <getopt.h>
	#include "common/common.h"
	#include "x264cli.h"

#include "libswscale/swscale.h"
}



x264_param_t param;
x264_t * x;
int c = 0;
uint8_t *buffer;
int buf_size;
x264_picture_t  pic_in,pic_out;
struct SwsContext* convertCtx = 0;
int fps = 25;
int width;
int height;

void x264_init(int w,int h){
	x264_param_default(&param);
	//x264_param_default_preset(&param, "veryfast", "zerolatency");

	param.i_threads = 1;
	param.i_width = w;
	param.i_height = h;
	param.i_fps_num = fps;
	param.i_fps_den = 1;

	// Intra refres:
	param.i_keyint_max = fps;
	param.b_intra_refresh = 1;
	//Rate control:
	param.rc.i_rc_method = X264_RC_CRF;
	param.rc.f_rf_constant = 25;
	param.rc.f_rf_constant_max = 35;
	//For streaming:
	param.b_repeat_headers = 1;
	param.b_annexb = 1;
	x264_param_apply_profile(&param, "baseline");

	x = x264_encoder_open(&param);
	//x264_picture_alloc( &pic_in, X264_CSP_BGRA, param.i_width, param.i_height );
	x264_picture_alloc( &pic_in, X264_CSP_I420, param.i_width, param.i_height );

	convertCtx = sws_getContext(w, h, PIX_FMT_ARGB, w, h, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
}

void x264_add(const uint8_t *pBits,int sz){

	int srcstride = width *3;
	
	sws_scale(convertCtx, &pBits, &srcstride, 0, height, pic_in.img.plane, pic_in.img.i_stride);

	/*memcpy(pic.img.plane[0],pBits,sz);
	pic.i_pts = param.i_fps_den * c; //timestamp
	pic.i_type = X264_TYPE_AUTO; //frame type, let x264 decide
	pic.i_qpplus1 = 0; //frame qp adjustment*/

	x264_nal_t * nal;
	int i_nal;

	
	int frame_sz = x264_encoder_encode(x,&nal,&i_nal,&pic_in,&pic_out);
	if (frame_sz >= 0){
		for( int i = 0; i < i_nal; i++ ) {
			x264_nal_encode( x,buffer, &nal[i] );
			//write buffer to file ...
		}
	}
	
	//c++;
}

void x264_close(){
	x264_picture_t  pic_null;

	
	x264_nal_t * p_nal;
	int i_nal;
	x264_encoder_encode(x,&p_nal,&i_nal,&pic_null,&pic_out);

	x264_encoder_close(x);
	x264_picture_clean(&pic_in);
	x264_picture_clean(&pic_out);
}